package com.qf.config;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.respVo.BaseResp;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if (method.equals("OPTIONS")){
            return true;
        }
        //1.从request请求中获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies==null||cookies.length==0){
            writeResponse(response,new BaseResp(0,"用户未登录！",null,null));
            return false;
        }else{
            String token=null;
            for (Cookie cook:cookies
                 ) {
                if (cook.getName().equals("token")){
                    token=cook.getValue();
                }
            }
            if (token==null||token.trim().isEmpty()){
                writeResponse(response,new BaseResp(0,"用户未登录！",null,null));
                return false;
            }else {
                //从redis中获取到Token值
                Boolean aBoolean = redisTemplate.hasKey(token);
                if (!aBoolean){
                    writeResponse(response,new BaseResp(0,"登录失效请重新登录！",null,null));
                    return false;
                }else{
                    Object o = redisTemplate.opsForValue().get(token);
                    Integer verfiy = jwtUtils.verfiy(o.toString());
                if (verfiy==0){
                    writeResponse(response,new BaseResp(0,"token失效！",null,null));
                    return false;
                }else {
                    //如果认证通过，则需要延长改key的时长
                    redisTemplate.expire(token,30, TimeUnit.MINUTES);
                    return true;
                }
             }
            }
        }

    }

    public static void writeResponse(HttpServletResponse response, BaseResp baseResp){
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            String o = JSONObject.toJSONString(baseResp);
            writer.write(o);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.flush();
            writer.close();
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


}
